﻿
/*
AutoGrow jQuery Plugin 1.0
Created: 2011-07-21
http://nasa8x.com
Copyright (c) 2011 Nasa8x
Dual licensed under the MIT and GPL licenses:
http://www.opensource.org/licenses/mit-license.php
http://www.gnu.org/licenses/gpl.html
*/

(function ($) {
    $.AutoGrow = function (obj, options) {
        this.input = obj;
        this.options = options;
        this.init();
    };

    $.AutoGrow.prototype = {
        init: function () {
            var me = this.input, o = this.options;
            this.minHeight = o.minHeight || parseInt(me.css('min-height'));
            this.maxHeight = o.maxHeight || parseInt(me.css('max-height'));
            this.height = me.height();
            this.dummy = me.clone().removeAttr("id").removeAttr("name").css({
                position: 'absolute',
                'overflow-y': 'auto',
                top: 0,
                width: me.width(),
                left: -99999
            }).attr('tabIndex', '-1').appendTo("body");

            me.attr('autogrow','1').css({ overflow: 'hidden' }).unbind('.autogrow').bind('keyup.autogrow keydown.autogrow change.autogrow', $.proxy(this.resize, this));

        },

        resize: function () {
            this.dummy.height(0).val(this.input.val());

            var h = Math.max(this.dummy.get(0).scrollHeight, this.height);

            if (this.lastSize === h) { return; }
            this.lastSize = h;
            if (this.minHeight > 0 && h < this.minHeight) {
                return;
            }

            if (this.maxHeight > 0 && h >= this.maxHeight) {
                this.input.css('overflow-y', 'auto');
                h = this.maxHeight;
            }
            else {
                this.input.css('overflow-y', 'hidden');
            }

            // resize callback
            if ($.isFunction(this.options.onResize))
                this.options.onResize.call(this);

            this.input.stop().animate({ height: h }, 200);
        }
    };

    $.fn.autogrow = function (o) {
        return this.each(function () {
            var me = $(this);
            if (me.attr('autogrow') == '1')
                return;
            var s = $.extend({}, o || {}, $.metadata ? me.metadata() : $.meta ? me.data() : {});
            new $.AutoGrow(me, s);

        });
    };

})(jQuery);